<?php

namespace App\Modules\User;


use App\Components\User\Models\MobileVerificationCode;
use App\Exceptions\StandardException;
use App\Library\Lock;
use App\Modules\User\Models\Member;
use App\Modules\User\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Ramsey\Uuid\Uuid;

class Manager
{
    public static function registerWeChat($unionid, array $data)
    {
        return self::getRegisterLock($unionid, function () use($unionid, $data) {
            $query = User::query()
                ->where('unionid', $unionid);
            $user = $query->first();
            if (is_null($user)) {
                /** @var User $user */
                $user = User::query()
                    ->create([
                        'unionid' => $unionid,
                        'session_key' => $data['sessionKey']??null,
                        'nickname' => $data['nickname']??null,
                        'avatar' => $data['avatar']??null,
                    ]);
            } else {
                $tmp = [
                    'session_key' => $data['sessionKey']??null,
                ];
                if (isset($data['avatar'])) {
                    $tmp['avatar'] = $data['avatar'];
                }
                if (isset($data['nickname'])) {
                    $tmp['nickname'] = $data['nickname'];
                }
                $user->update($tmp);
            }
            if (empty($user->openid) && !empty($data['openid'])) {
                User::query()->where('openid', $data['openid'])->update([
                    'openid' => null,
                ]);
                $user->openid = $data['openid'];
            }
            if (empty($user->official_account_openid) && !empty($data['official_account_openid'])) {
                $user->official_account_openid = $data['official_account_openid'];
            }
            $user->save();
            return $user;
        });
    }

    public static function getUserByOpenid($openid)
    {
        return User::query()->where('openid', $openid)->first();
    }

    public static function registerTmp($openid, $sessionKey)
    {
        return User::query()
            ->updateOrCreate([
                'openid' => $openid,
            ], [
                'session_key' => $sessionKey,
            ]);
    }
    public static function getRegisterLock($openId, $callback)
    {
        return Lock::lock("user:register:{$openId}", 2, $callback);
    }

    public static function getInviteCode()
    {
        $incr = Redis::incr("invite:incr");
        $random = random_int(0, 9);
        return $random.str_pad($incr, 5, "0", STR_PAD_LEFT);
    }

    public static function setMember(User $user, $shopId, $price)
    {
        /** @var Member $member */
        $member = Member::query()
            ->where('user_id', $user->id)
            ->where('shop_id', $shopId)
            ->first();
        if (is_null($member)) {
            Member::query()
                ->create([
                    'user_id' => $user->id,
                    'shop_id' => $shopId,
                    'quota' => $price,
                    'rebate' => 0,
                ]);
        } else {
            $member->increment('quota', $price);
        }
    }

    public static function createMobileVerification(User $user, string $areaCode, string $mobile)
    {
        $exists = User::query()
            ->where('mobile', $mobile)
            ->exists();

        if ($exists) {
            throw new StandardException('该手机号已被绑定');
        }

        /** @var MobileVerificationCode $code */
        $code = MobileVerificationCode::create([
            'serial_number' => Uuid::uuid4()->getHex(),
            'user_id' => $user->id,
            'area_code' => $areaCode,
            'mobile' => $mobile,
            'code' => sprintf('%06d', random_int(000000, 999999)),
        ]);

        $code->send();

        return $code->result_biz_id;
    }

    /**
     * 原来的方法。现在改为用微信的获取手机号的方式
     */
    // public static function checkMobileVerification(User $user, $bizId, $code)
    // {
    //     $timeLimit = now()->subMinute(10)->toDateTimeString();

    //     /** @var MobileVerificationCode $record */
    //     $record = MobileVerificationCode::query()
    //         ->where('result_biz_id', $bizId)
    //         ->where('user_id', $user->id)
    //         ->where('code', $code)
    //         ->where('created_at', '>=', $timeLimit)
    //         ->first();
    //     if (is_null($record)) {
    //         throw new StandardException('验证码错误');
    //     }
    //     self::getMobileLock($record->mobile, 10, function () use ($user, $record) {
    //         $mobileUser = User::query()
    //             ->where('mobile', $record->mobile)
    //             ->first();
    //         if (!is_null($mobileUser)) {
    //             throw new StandardException('该手机号已被绑定');
    //         }
    //         $record->update(['checked' => true]);
    //         $user->mobile = $record->mobile;
    //         $user->save();
    //     });

    // }

    /**
     * 绑定手机号  验证接口
     * @param  User   $user  [用户信息]
     * @param  $mobile [电话号]
     */
    public static function checkMobileVerification(User $user, $mobile)
    {
        self::getMobileLock($mobile, 10, function () use ($user, $mobile) {

            $mobileUser = User::query()->where('mobile', $mobile)->where('id', '!=', $user->id)->first();
            if (!is_null($mobileUser)) {
                throw new StandardException('该手机号已被绑定');
            }
            $user->mobile = $mobile;
            $user->save();
        });
    }

    public static function getMobileLock($mobile, $tll, $callback)
    {
        return Lock::lock("user:mobile:".$mobile, $tll, $callback);
    }
}
